/**
 * 
 */
package neptune.web.client.controller;

import neptune.web.client.WebInterface;
import neptune.web.client.model.DefaultRoles;
import neptune.web.client.services.ApplicationDataProvider;
import neptune.web.client.services.user.LogInService;
import neptune.web.client.services.user.LogInServiceAsync;
import neptune.web.client.view.ConsoleManager;
import neptune.web.client.view.HistoryTokenUtils;
import neptune.web.client.view.LogInView;
import neptune.web.client.view.LogInViewListener;
import neptune.web.client.view.OperativeView;
import neptune.web.client.view.ViewManager;
import neptune.web.client.view.components.AdminMenuBar;
import neptune.web.client.view.components.UserMenuBar;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * @author Roberto Bifulco [info@robertobifulco.it, robertobifulco.it]
 * 
 */
public class LogInController implements LogInViewListener {

	private LogInServiceAsync loginHandler = LogInService.Util.getInstance();

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * neptune.web.client.view.LogInViewListener#logInStarted(java.lang.String,
	 * java.lang.String)
	 */
	public void logInStarted(final String username, String password,
			LogInView sender) {
		loginHandler.login(username, password, new AsyncCallback<String>() {

			public void onSuccess(String result) {
				ConsoleManager.addConsoleMessage("Log In successed", false);
				History.newItem(HistoryTokenUtils.buildToken("",
						OperativeView.DEFAULT_TOKEN));

				OperativeView view = (OperativeView) ViewManager
						.getViewManager().getViewByName(
								OperativeView.DEFAULT_TOKEN);
				view.setUsernameLabel(username, (String) result);

				// Aggiorna le informazioni sull'attuale ruolo utente.
				ApplicationDataProvider.getInstance().setActualUserRole(
						(String) result);
				ApplicationDataProvider.getInstance().setActualUserName(
						username);
				// Imposta l'intervallo di polling per il recupero dei dati dal
				// server. Questa impostazione consente di mantenere sempre
				// aperta la connessione client
				ApplicationDataProvider
						.getInstance()
						.getTimer()
						.scheduleRepeating(
								ApplicationDataProvider.AUTO_UPDATE_INTERVAL);

				if (((String) result).equals(DefaultRoles.SYSTEM_ADMIN))
					view.setTopMenuBar(new AdminMenuBar());
				else
					view.setTopMenuBar(new UserMenuBar());

				WebInterface.updateViewsOfOperativeView();
			}

			public void onFailure(Throwable caught) {
				ConsoleManager.addConsoleMessage("Log In failed: "
						+ caught.getMessage(), true);
			}

		});
	}

}
